package com.ebupt.migu.music.siginIn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.TokenUtils;
import com.ebupt.migu.music.siginIn.mapper.SiginInMapper;
import com.ebupt.migu.music.siginIn.service.SiginInService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SiginInServiceImpl implements SiginInService {

    @Resource
    private SiginInMapper siginInMapper;

    @Value("${siginIn.recommendURL}")
    private String recommendURL;

    @Value("${siginIn.aesSecretKey}")
    private String aesSecretKey;
    /**
     * 同步服务云运营平台用户信息到推荐运营系统(一级系统)
     * @param map
     * @return
     */
    @Override
    public ResultObject synchroniUserWalle(Map<String,Object> map) {
        ResultObject resultObject =  new ResultObject();
        //设置公司ID，companyId统一为3
        map.put("companyId","3");
        //设置是否为OA用户：1-是，0-不是 统一为0
        map.put("isOaOperator","0");
        //项目名称
        map.put("projectName","music");
        //map转json,并且转成string格式
        log.info("synchroniUserWalle==map:"+map.toString());
        String s = JSONObject.toJSONString(map);
        JSONObject jsonParam=null;
        try{
            //然后将转成的对象进行公钥加密
            String userInfo = AESUtil.encrypt(s,aesSecretKey);
            jsonParam= new JSONObject();
            jsonParam.put("userInfo",userInfo);
            jsonParam.put("type",1);
            jsonParam.put("companyId",3);
            log.info("synchroniUserWalle===:"+jsonParam.toString());
            String respString = TestUtils.post(recommendURL,jsonParam.toString(),"UTF-8");
            log.info("respString====:"+respString);
            //判断请求是否成功
            if (respString !=null && respString.length()>0) {
                //获取响应内容，转换成JSON
                JSONObject resp = JSONObject.parseObject(respString);
                //判断返回状态
                String code = resp.getString("code");
                String message = resp.getString("message");
                log.info("synchroniUserWalle:==code:"+code);
                if ("200".equals(code)){
                    //200代表权限分配成功，给前端返回musicToken
                    resultObject.setCode("200");
                    resultObject.setMsg(StatusEnum.SUCCESS.getMsg());
                    //生成token,并且将token加密，然后发送给前端
                    String token = TokenUtils.createJwtToken(map.get("loginName")+"");
                    String musicToken = AESUtil.encrypt(token,aesSecretKey);
                    resultObject.setCode("200");
                    resultObject.setMsg("成功");
                    resultObject.setData(musicToken);
                    return resultObject;
                }else {
                    resultObject.setCode(code);
                    resultObject.setMsg(message);
                    return resultObject;
                }
            }else {
                resultObject.setCode(StatusEnum.ERROR.getCode());
                resultObject.setMsg("服务器异常，验证用户失败!");
                return resultObject;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        resultObject.setCode(StatusEnum.ERROR.getCode());
        resultObject.setMsg("服务器异常，验证用户失败!");
        return resultObject;
    }

    /**
     * 单点登录TOKEN验证接口
     * @param map
     * @return
     */
    @Override
    public JSONObject getSiginUserInfo(Map<String, Object> map) {
        String token = (String) map.get("token");
        JSONObject jsonParam=new JSONObject();
        Claims claims = null;
        log.info("token===:"+token);
        try {
            //判断token是否正确，并且解析token
            claims = TokenUtils.parseJWT(token);
        }catch (Exception e){
            jsonParam.put("code","404");
            jsonParam.put("message","token不正确");
            log.info("getSiginUserInfo===erro==:"+e.getMessage());
            return jsonParam;
        }
        String loginName =  claims.getId().trim();
        log.info("name:-=="+loginName);
        //根据用户账号查询用户信息
        List<Map<String,Object>> authUsers = siginInMapper.queryAuthUser(loginName);
        if (authUsers.size()>0){
            //map转json,并且转成string格式
            Map<String,Object> userMap = authUsers.get(0);
            //设置公司ID，companyId统一为3
            userMap.put("companyId","3");
            //设置是否为OA用户：1-是，0-不是 统一为0
            userMap.put("isOaOperator","0");
            //项目名称
            userMap.put("projectName","music");
            log.info("getSiginUserInfo==userMap:"+userMap.toString());
            String s = JSONObject.toJSONString(userMap);
            //将用户信息加密
            try{
                String userInfo = AESUtil.encrypt(s,aesSecretKey);
                jsonParam.put("code","200");
                jsonParam.put("message","成功");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userInfo",userInfo);
                jsonParam.put("data",jsonObject);
            }catch (Exception e){
                e.printStackTrace();
            }
            log.info("接口返回值：{}", jsonParam.toJSONString());
            return jsonParam;
        }else {
            jsonParam.put("code","500");
            jsonParam.put("message","用户信息获取失败");
            return jsonParam;
        }
    }

}
